#!/bin/bash

# docker
sudo apt-get update
sudo apt-get install docker.io
sudo usermod -aG docker ${USER}

# fix docker issue
cat <<EOF | sudo tee /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

sudo systemctl enable docker
sudo systemctl daemon-reload
sudo systemctl restart docker


# iptables
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
EOF

cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward=1 # better than modify /etc/sysctl.conf
EOF

sudo sysctl --system

# Disable Swap
sudo swapoff -a
sudo sed -ri '/\sswap\s/s/^#?/#/' /etc/fstab

# kubeadm kubelet kubectl
sudo apt install -y apt-transport-https ca-certificates curl nfs-common
curl https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | sudo apt-key add -
cat <<EOF | sudo tee /etc/apt/sources.list.d/kubernetes.list
deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main
EOF
sudo apt update
sudo apt install -y kubeadm=1.23.3-00 kubelet=1.23.3-00 kubectl=1.23.3-00
sudo apt-mark hold kubeadm kubelet kubectl
kubeadm version
kubectl version --client

# images
repo=registry.aliyuncs.com/google_containers
for name in `kubeadm config images list --kubernetes-version v1.23.3`;
do
	# remove prefix
	src_name=${name#k8s.gcr.io/}
	src_name=${src_name#coredns/}

	sudo docker pull $repo/$src_name

	# rename to fit k8s
	sudo docker tag $repo/$src_name $name
	sudo docker rmi $repo/$src_name
done

# kubeadm init --control-plane-endpoint=192.168.0.231 --cri-socket unix:///var/run/cri-dockerd.sock --image-repository="registry.aliyuncs.com/google_containers" --upload-certs --kubernetes-version v1.26.5
#sudo kubeadm init --pod-network-cidr=10.244.0.0/16 --image-repository="registry.aliyuncs.com/google_containers" --kubernetes-version=v1.23.3 --v=5
#mkdir -p $HOME/.kube
#sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
#sudo chown $(id -u):$(id -g) $HOME/.kube/config
#sudo chown $(id -u):$(id -g) $HOME/.kube/config/etc/kubernetes/admin.conf 

#wget https://github.com/flannel-io/flannel/blob/master/Documentation/kube-flannel.yml
#kubectl apply -f kube-flannel.yml

#kubeadm token create --print-join-command
#sudo kubeadm join 192.168.100.128:6443 --token h3moi3.dz16ja0zb4ujbm07 --discovery-token-ca-cert-hash sha256:d3457654441f4909aef22f767711e14a51b8556b6547140271cb9b29562d6d15

#wget  https://raw.githubusercontent.com/kubernetes/dashboard/v2.0.0-rc6/aio/deploy/recommended.yaml
#kubectl apply -f recommended.yml
